<!--
 * @Author: Lin Ming
 * @Date: 2021-02-25 14:57:42
 * @LastEditors: Lin Ming
 * @LastEditTime: 2021-02-25 18:20:55
 * @FilePath: \vue-zheye\src\components\ValidateForm.vue
-->
<template>
  <div class="lm-validate-form">
    <form class="validate-form-container">
      <slot name="default" />
      <div class="submit-area" @click.prevent="submitForm">
        <slot name="submit" >
          <button type="submit" class="btn btn-primary">提交</button>
        </slot>
      </div>
    </form>
  </div>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from 'vue'
import mitt from 'mitt'
type ValidateFunc = () => boolean
// 实例化 mitt
export const emitter = mitt()
export default defineComponent({
  name: 'ValidateForm',
  emits: ['form-submit'],
  setup (props, context) {
    let funcArr: ValidateFunc[] = []
    const submitForm = () => {
      const result = funcArr.map(func => func()).every(result => result)
      context.emit('form-submit', result)
    }
    // 将监听得到的验证函数都存到一个数组中
    // const callback = (func: boolean) => {
    //   funcArr.push(func)
    // }
    // function onFoo (func: ValidateFunc) {
    //   funcArr.push(func)
    // }
    // 添加监听
    emitter.on('form-item-created', func => funcArr.push(func))
    onUnmounted(() => {
      // 删除监听
      emitter.off('form-item-created', func => funcArr.push(func))
      funcArr = []
    })
    return {
      submitForm
    }
  }
})
</script>
